<template>
  <div>
  <el-tabs v-model="activeIndex" type="card" closable @tab-click="tabClick" @tab-remove="removeTab">
    <el-tab-pane
      type="border-card"
      v-for="(item, index) in options"
      :key="item.id"
      :label="item.title"
      closable
      :name="item.route">

    </el-tab-pane>
  </el-tabs>
  </div>
</template>

<script>
export default {
  name: 'layout-main-tabs',
  data(){
    return {

    }
  },
  created(){

  },
  computed: {
    options(){
      return this.$store.state.options;
    },
    activeIndex: {
      get () {
        return this.$store.state.activeIndex;
      },
      set (val) {
        this.$store.commit('set_active_index', val);
      }
    }
  },
  methods:{
    // tab切换时，动态的切换路由
    tabClick (tab) {

      let path = this.activeIndex;
      // 用户详情页的时候，对应了二级路由，需要拼接添加第二级路由
      if (this.activeIndex === '/userInfo') {
        path = this.activeIndex + '/' + this.$store.state.userInfo.name;
      }
      let id;
      for(let index in this.$store.state.options){
        if (this.activeIndex === this.$store.state.options[index].route){
          id = this.$store.state.options[index].id
        }
      }
      this.$router.push({path: path,query:{id:id}});

    },
    removeTab(targetName) {
      // 首页不可删除
      if(targetName == '/') {
        return;
      }
      this.$store.commit('delete_tabs', targetName);
      if (this.activeIndex === targetName) {
        // 设置当前激活的路由
        if (this.options && this.options.length >= 1) {
          this.$store.commit('set_active_index', this.options[this.options.length-1].route);
          this.$router.push({path: this.activeIndex});
        } else {
          this.$router.push({path: '/'});
        }
      }
    }
  },
  computed: {
    options(){
      return this.$store.state.options;
    },
    activeIndex: {
      get () {
        return this.$store.state.activeIndex;
      },
      set (val) {
        this.$store.commit('set_active_index', val);
      }
    }
  },
  watch: {
    '$route'(to) {
      let flag = false;
      for (let option of this.options ) {
        if (option.name === to.name) {
          flag = true;
          this.$store.commit('set_active_index', to.path);
          break
        }
      }
      if (!flag) {
        this.$store.commit('set_options', {route: to.path, name: to.name, title: to.name});
        this.$store.commit('set_active_index', to.path);
      }
    }
  },
}
</script>

<style scoped>

</style>
